package com.example.interceptor;

import com.example.service.SqnService;
import com.example.util.MsgContext;
import com.example.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TdLogInterceptor implements HandlerInterceptor {

    private static Logger log = LoggerFactory.getLogger(TdLogInterceptor.class);
    private String WEBCHANNEL = "Web";
    public static final SimpleDateFormat simpleDateFmt = new SimpleDateFormat("yyyyMMddHHmmss");
    SqnService sqn = new SqnService();

    /**
     * 功能描述:
     *
     * @Author: Administrator
     * @Date: 2018/8/10 16:17
     * @Param:
     * @Return:
     */
    public TdLogInterceptor() {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String s = getRequestURI(request);
        MsgContext cxt = createMsg(s);
        log.info("{} 交易开始执行 请求URI {}", cxt.getMessageId(), request.getRequestURI().toString());
        MDC.put("processid", cxt.getMessageId());
        return true;
    }

    //获取交易码

    private String getRequestURI(HttpServletRequest request) {
        /**
        * 功能描述:
        *
        * @Author: Administrator
        * @Date: 2018/8/10 16:25
        * @Params:  * @param request
        * @Return: java.lang.String
        */
        String reqUrl = request.getRequestURI();
        int index = reqUrl.lastIndexOf("/");
        reqUrl = "_" + reqUrl.substring(index + 1);

        return reqUrl;
    }

    MsgContext createMsg(String path) {
        long msgid = sqn.getSqn(WEBCHANNEL);
        String date = simpleDateFmt.format(new Date());
        String logName = String.format("%s%s%06d_%s", WEBCHANNEL, date, msgid, path);
        MsgContext ctx = new MsgContext(logName, WEBCHANNEL, System.currentTimeMillis());
        return ctx;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("{}交易执行完成", MDC.get("processid"));
        MDC.remove("processid");
        StringUtil.removeappnder("SIFT");
    }
}


